package filters;

import helpers.LanguageHelper;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import user.models.UserModel;

import entities.User;

public final class UrlFilter implements Filter {
	
	private static final Logger log = Logger.getLogger(UrlFilter.class
			.getName());
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		
		//Check user login
		User user = null;
		LanguageHelper languageTranslate = new LanguageHelper(req);
		if (req.getUserPrincipal() != null) {
			UserModel userModel = UserModel.getInstance();
			user = userModel.getByUsername(req.getUserPrincipal().getName());
		}
		request.setAttribute("user_logged_in", user);
		request.setAttribute("language", languageTranslate.getLanguage());
		
		chain.doFilter(request, response);
		return;
	}

	public void destroy() {

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}
}